package com.tang.wx.controller;

import com.tang.wx.handler.WxMsgFactory;
import com.tang.wx.handler.WxMsgHandler;
import com.tang.wx.utils.SHA1Util;
import com.tang.wx.utils.WxMsgUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Optional;

@Slf4j
@RestController
public class CallbackController {

    @Value("${wx.token}")
    private String token;

    @Resource
    private WxMsgFactory wxMsgFactory;

    /**
     * 微信平台验签
     *
     * @param signature 微信加密签名
     * @param timestamp 时间戳
     * @param nonce     随机数
     * @param echostr   随机字符串
     * @return java.lang.String
     * @author Tang
     * @date 2024/2/17 10:25
     **/
    @GetMapping("/callback")
    public String callback(@RequestParam(defaultValue = "signature") String signature,
                           @RequestParam(defaultValue = "timestamp") String timestamp,
                           @RequestParam(defaultValue = "nonce") String nonce,
                           @RequestParam(defaultValue = "echostr") String echostr) {
        if (log.isInfoEnabled()) {
            log.info("微信加密签名：{}，时间戳：{}，随机数：{}，随机字符串：{}", signature, timestamp, nonce, echostr);
        }
        String shaStr = SHA1Util.getSHA1(token, timestamp, nonce, "");
        if (StringUtils.equals(shaStr, signature)) {
            return echostr;
        }
        return "unknown";
    }

    /**
     * 微信消息回调
     *
     * @param requestBody  消息体
     * @param signature    微信加密签名
     * @param timestamp    时间戳
     * @param nonce        随机数
     * @param msgSignature
     * @return java.lang.String
     * @author Tang
     * @date 2024/2/17 10:27
     **/
    @PostMapping(value = "/callback", produces = "application/xml;charset=UTF-8")
    public String callback(@RequestBody String requestBody,
                           @RequestParam(defaultValue = "signature") String signature,
                           @RequestParam(defaultValue = "timestamp") String timestamp,
                           @RequestParam(defaultValue = "nonce") String nonce,
                           @RequestParam(value = "msg_signature", required = false) String msgSignature) {
        if (log.isInfoEnabled()) {
            log.info("微信消息体：{},微信加密签名：{}，时间戳：{}，随机数：{}，随机字符串：{}", requestBody, signature, timestamp, nonce, msgSignature);
        }
        Map<String, String> msgMap = WxMsgUtil.parseXml(requestBody);
        String msgType = WxMsgUtil.getMsgType(msgMap);
        WxMsgHandler handlerByMsgType = wxMsgFactory.getHandlerByMsgType(msgType);
        return Optional.ofNullable(handlerByMsgType)
                .map(i->handlerByMsgType.handleMsg(msgMap))
                .orElse("");
    }
}
